<?php
/**
 * Created by PhpStorm.
 * User: david
 * Date: 2018/5/24
 * Time: 17:40
 */

namespace app\admin\controller;


use app\admin\Controller;
use app\common\model\Post as PostModel;
use app\common\model\PostMenu as PostMenuModel;
use think\Db;
use think\Session;
use traits\controller\Jump;

class Post extends Controller
{
    use \app\admin\traits\controller\Controller;
    use Jump;

    public function addpost()
    {
        if ($this->request->isGet()) {
            $menus = PostMenuModel::getMenus();
            $this->view->assign('menus', $menus);
            return $this->view->fetch('addpost');
        }
        $data = $this->request->param()['data'];
        $data['content'] = urldecode($data['content']);
        if (empty($data['description'])) {
            $data['description'] = $this->_getSummary(urldecode($data['content']));
        }
        $data['author'] = $this->author(Session::get('auth_id'));
        $time = time();
        $data['create_time'] = $time;
        $data['update_time'] = $time;
        PostModel::create($data);
        return [
            'code' => 0,
            'msg' => 'success'
        ];
    }

    private function author($auth_id)
    {
        if ($auth_id == 1) {
            return '超级管理员';
        }
        $role_id = Db::name('admin_role_user')->where('user_id', $auth_id)->find();
        $user = Db::name('admin_user')->find($auth_id);
        if ($role_id && $user) {
            $role = Db::name('admin_role')->find($role_id);
            return $role['name'] . '：' . $user['realname'];
        }
        return null;
    }

    public function preview($id)
    {
        $post = PostModel::get($id);
        $this->view->assign('post', $post);
        return $this->view->fetch();
    }

    private function _getSummary($content,$s = 0,$e = 150,$char = 'utf-8')
    {
        if (empty($content)) {
            return null;
        }
        return (mb_substr(str_replace('&nbsp;', '', strip_tags($content)), $s, $e, $char));
    }

    /*私有文章图片提取方法*/
    private function _getImg($str)
    {
        if (empty($str)) {
            return null;
        }
        $pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";
        preg_match_all($pattern,$str,$match);
        return $match[1][0];
    }

    public function edit($id)
    {
        if ($this->request->isAjax()) {
            $data = $this->request->param()['data'];
            $data['content'] = urldecode($data['content']);
            PostModel::where('id', $id)->update($data);
            return [
                'code' => 0,
                'msg' => 'success'
            ];
        } else {
            $post = PostModel::get($id);
            $menus = PostMenuModel::getMenus();
            $this->view->assign('menus', $menus);
            $this->view->assign('post', $post);
            return $this->view->fetch('editpost');
        }
    }
}